/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package huffman;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.TreeSet;

/**
 *
 * @author apostol
 */
public class Huffman
{
        static int nrElem = 0;
        static int FileSize = 0;
	public static void mainHuff(String pathToFile)
		throws IOException
	{
		StringBuffer continutFisier = new StringBuffer();
          
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                InputStream inputStream = new FileInputStream(pathToFile);
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

		String line = null;
		while ((line = br.readLine()) != null)
			continutFisier.append("\n").append(line);
                FileSize = continutFisier.length();
		proceseazaFisier(continutFisier.toString());
	}

	private static void proceseazaFisier(String sirContinutFisier)
	{
		nrElem =0;
                int[] frequency = new int[90000];		// Tabela de frecvente
		TreeSet<Node> trees	= new TreeSet<Node>();	// Lista care contine vectorul ordonat

		// Construim vectorul de ocurente in textul dat
		char ch;
                for (int i=0; i<sirContinutFisier.length(); i++)
		{
                    ch = sirContinutFisier.charAt(i);
                    ++frequency[ch];
		}
		// Construirea arborelui initial
		for (int i=0; i<90000; i++)
		{
			if (frequency[i] > 0)//10-cod ascii de newline
			{
				Node n = new Node((char)(i), frequency[i]);
				trees.add(n);
                                System.out.println((char)i+" "+(float)frequency[i]/(float)FileSize);
                                nrElem++;
			}
		}

		// Algoritm huffman
		while (trees.size() > 1)
		{
			Node tree1 = (Node) trees.first();
			trees.remove(tree1);
			Node tree2 = (Node) trees.first();
			trees.remove(tree2);

			Node merged = new Node(tree1, tree2);
			trees.add(merged);
		}

		// Afisarea arborelui Huffman
		if (trees.size() > 0)
		{
			Node theTree = (Node) trees.first();
			Node.afiseazaArbore(theTree);
                }
		else
			System.out.println("eroare");
	}
}
